package com.buyi.easyhome.receiver

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.BatteryManager
import android.util.Log
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkManager
import androidx.work.WorkRequest
import androidx.work.workDataOf
import com.buyi.easyhome.R
import com.buyi.easyhome.util.BatteryAlarmType
import com.buyi.easyhome.util.CommonUtils
import com.buyi.easyhome.worker.PlayTextWorker

class ScreenBroadcastReceiver : BroadcastReceiver() {
    private val TAG = "ScreenBroadcastReceiver"

    override fun onReceive(context: Context, intent: Intent) {
        if (intent.action == Intent.ACTION_SCREEN_ON) {
            val batteryStatus: Intent? =
                IntentFilter(Intent.ACTION_BATTERY_CHANGED).let { ifilter ->
                    context.registerReceiver(null, ifilter)
                }

            // 获取充电状态
            val status = batteryStatus?.getIntExtra(BatteryManager.EXTRA_STATUS, -1) ?: -1
            val isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING
                    || status == BatteryManager.BATTERY_STATUS_FULL
            Log.d(TAG, "onReceive: status: $status isCharging: $isCharging")

            // 获取电池电量
            val level = batteryStatus?.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) ?: -1
            val scale = batteryStatus?.getIntExtra(BatteryManager.EXTRA_SCALE, -1) ?: -1

            // 计算电池百分比
            val batteryPct = level * 100 / scale.toFloat()
            val batteryPctInt = batteryPct.toInt()
            Log.d(
                TAG,
                "onReceive: batteryPct: $batteryPct batteryPctInt: $batteryPctInt"
            )

            val message = "电量$batteryPctInt"

            val playTextWorkRequest: WorkRequest =
                OneTimeWorkRequestBuilder<PlayTextWorker>()
                    .setInputData(
                        workDataOf(
                            "playType" to BatteryAlarmType.TTS.name,
                            "textToSpeechText" to message,
                            "resids" to intArrayOf(R.raw.tts_battery_power) + CommonUtils.getResids(
                                batteryPctInt.toString()
                            ),
                        )
                    )
                    .build()
            WorkManager.getInstance(context)
                .enqueue(playTextWorkRequest)

            Log.d(TAG, "onReceive: finish!")
        }
    }
}